package com.tuo51.childcare.service.impl;

import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.tuo51.evaluate.domain.evaluatingV2.EvaluateV2Record;
import com.tuo51.evaluate.repositories.evaluatev2.EvaluateV2RecordRepository;
import com.tuo51.evaluate.service.appuser.PaymentService;
import com.tuo51.foudation.exception.BusinessException;
import com.tuo51.foudation.model.ErrorCode;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

import static com.tuo51.foudation.constant.APPConstants.PayObjectType.REPORT;

@Service
public class MPPaymentService {

    @Autowired
    PaymentService paymentService;

    @Autowired
    WxPayService mpPayService;

    @Autowired
    EvaluateV2RecordRepository recordRepository;

    @Transactional(rollbackFor = RuntimeException.class)
    public Map<String,Object> createWxReportOrder(String userId, long productId, String reportId, String code ) throws WxPayException, JSONException {

        EvaluateV2Record record = recordRepository.getOne(reportId);
        if (record == null){
            throw new BusinessException(ErrorCode.EVALUATE_RECORD_NOT_EXIST, "报告不存在");
        }

        if (record.getPaid()){
            throw new BusinessException(ErrorCode.REPORT_ALREADY_PAID, "已经是付费状态，不需要重复支付。");
        }

        return paymentService.createWxOrder(userId, productId, REPORT.getValue(), reportId, code, mpPayService);
    }

}
